package 内存可见性;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:这里while本来循环非常快,而且内存的读取数据远小于CPU里寄存器的读取数据,编译器优化只会读取一次内存里的数据
 * User: lenovo
 * Date: 2022-09-24
 * Time: 15:12
 */
public class Demo1 {
    static class Counter{
         public  int count;//volatile 可以让编译器继续读取内存里的counter.count 即不优化

    }
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(){
            @Override
            public void run() {
                while (counter.count == 0){

                }
                System.out.println("t1线程执行结束");
            }
        };
        t1.start();

        Thread t2 = new Thread(){
            @Override
            public void run() {
                System.out.println("请输入数字:");
                Scanner scanner = new Scanner(System.in);
                counter.count = scanner.nextInt();
            }
        };
        t2.start();
//        Thread t3 = new Thread(){
//            @Override
//            public void run() {
//                counter.count =1;
//            }
//        };
//        t3.start();
    }
}
